package cn.com.nes.site.rocketmq.handler;

import cn.com.nes.mybatis.agent.system.entity.Company;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.vo.user.SaveBusinessCompanyVo;
import cn.com.nes.site.module.service.UserService;
import cn.com.nes.site.rocketmq.strategy.MessageHandler;
import cn.com.nes.site.rocketmq.strategy.Topic;
import cn.com.nes.site.service.system.company.BusinessCompanyService;
import cn.com.nes.site.service.system.company.CompanyMerchantService;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Topic("mall2agent_merchant_topic")
@Component
@Slf4j
public class Mall2AgentMerchantHandler implements MessageHandler {

    @Resource
    private BusinessCompanyService businessCompanyService;

    @Resource
    private CompanyMerchantService companyMerchantService;

    @Resource
    private UserService userService;

    public void handleMessage(MessageExt message) {
        log.info("处理 mall2agent_merchant_topic 消息:{}", new String(message.getBody()));
        try {
            // 获取消息入参对象
            String messageBody = new String(message.getBody());
            ObjectMapper objectMapper = new ObjectMapper();
            SaveBusinessCompanyVo saveBusinessCompanyVo = objectMapper.readValue(messageBody, SaveBusinessCompanyVo.class);

            // 由于统一社会信用代码更改为可修改逻辑,所以不再具有唯一性
            // 根据店铺id查询关联公司的信息
            Company company;
            try {
                String companyId = companyMerchantService.queryCompanyIdByMerId(Integer.valueOf(saveBusinessCompanyVo.getMerchantId()));

                company = businessCompanyService.getCompany(companyId);
            } catch (Exception e) {
                log.error("根据店铺id查询关联的公司信息异常,切换为使用统一社会信用代码匹配公司");
                company = null;
            }
            // 如果根据店铺id匹配到了公司 - 修改公司信息
            if (ObjectUtil.isNotNull(company)) {
                // 更新公司信息
                updateCompanyInfo(company, saveBusinessCompanyVo);
                // 程序结束
                return;
            }

            // 如果店铺id未匹配到任何公司,那么根据统一社会信用代码查询公司 - 先查询公司是否已经存在,存在就绑定且更新,不存在则新增公司数据
            String companyId = processCompany(saveBusinessCompanyVo.getUniformSocialCreditCode(), saveBusinessCompanyVo);

            if (ObjectUtil.isNotNull(companyId)) {
                // 建立公司与商铺的关系
                companyMerchantService.processCompanyMerchant(companyId, saveBusinessCompanyVo);
                // 建立公司与用户关系 - 创建默认管理员账号
                userService.processSuperAdminUser(companyId, saveBusinessCompanyVo, null);
            }
        } catch (Exception e) {
            log.error("异常原因:" + e);
            System.err.println("消息处理失败: " + e.getMessage());
        }
    }

    private String processCompany(String uniformSocialCreditCode, SaveBusinessCompanyVo saveBusinessCompanyVo) throws Exception {
        // 根据统一社会信用代码查询公司
        List<Company> companyList = businessCompanyService.getCompanyByUniformSocialCreditCode(uniformSocialCreditCode);
        // 公司不存在，新增公司
        if (CollectionUtil.isEmpty(companyList)) {
            PageData pageData = businessCompanyService.saveBusinessCompany(saveBusinessCompanyVo);
            return pageData.getKey();  // 返回新增的公司ID
        }
        // 取出第一个公司信息
        Company company = companyList.get(0);
        // 更新公司数据
        updateCompanyInfo(company, saveBusinessCompanyVo);
        // 返回公司的ID
        return company.getCompanyid();
    }

    /**
     * 更新公司数据
     */
    private void updateCompanyInfo(Company company, SaveBusinessCompanyVo vo) {
        try {
            // 必填项
            company.setUniformsocialcreditcode(vo.getUniformSocialCreditCode());
            company.setLegalperson(vo.getLegalPerson());
            company.setAddress(vo.getRegisterAddress());
            company.setAreacode(vo.getAreaCode());
            // 非必填项
            company.setCompanyname(vo.getCompanyFullName());
            company.setShortname(vo.getCompanyShortName());
            company.setOrganizationCode(vo.getOrganizationCode());
            company.setContact(vo.getContact());
            company.setContactnumber(vo.getContactNumber());
            company.setChannel(vo.getChannel());
            company.setGmtModified(vo.getOperateDate());
            company.setGmtModifiedId(vo.getOperateUserId());

            boolean success = businessCompanyService.updateById(company);
            if (!success) {
                throw new Exception("更新公司数据失败!");
            }
        } catch (Exception e) {
            log.error("更新公司数据失败!失败原因:", e);
        }
    }
}
